<?php
namespace TwOauth;

/**
 * Description of tongwei
 *
 * @author company
 */
class Tongwei
{

    const APP_KEY = 'e89466d3d3f0eb2715d8a4ca';

    const APP_SECRET = '235HJaeQ60kJ8mJ7DB50bsXVKJXx1CKl';

    protected $recorder;

    protected $error;

    protected $urlUtils;

    protected $redirect_uri;

    protected $access_token_url;

    protected $auth_code_url;

    public function __construct($redirect_uri)
    {
        $this->recorder = new Recorder();
        $this->error = new ErrorCase();
        $this->urlUtils = new URL();
        $this->redirect_uri = $redirect_uri;
    }

    public function getCodeUrl()
    {
        $this->auth_code_url = Config::getOauthCode();
        return $this->auth_code_url;
    }

    public function getAccessTokenUrl()
    {
        $this->access_token_url = Config::getAccessToken();
        return $this->access_token_url;
    }

    public function login()
    {
        // -------生成唯一随机串防CSRF攻击
        $state = md5(uniqid(rand(), TRUE));
        $this->recorder->write('state', $state);
        // -------构造请求参数列表
        $params = array();
        $params['app_key'] = self::APP_KEY;
        $params['redirect_uri'] = urlencode($this->redirect_uri);
        $params['response_type'] = 'code';
        $params['scope'] = 'basic';
        $params['state'] = $state;
        $code_url = $this->getCodeUrl() . "?" . http_build_query($params);
        return $code_url;
        // return header('Location: ' . $code_url);
        // exit();
    }

    public function callBack()
    {
        $state = $this->recorder->read('state');
        // --------验证state防止CSRF攻击
        if ($_GET['state'] != $state) {
            $this->error->showError("30001");
        }
        
        // -------请求参数列表
        $keysArr = array(
            "grant_type" => "authorization_code",
            "app_key" => self::APP_KEY,
            "redirect_uri" => urlencode($this->redirect_uri),
            "app_secret" => self::APP_SECRET,
            "code" => $_GET['code']
        );
        
        // ------构造请求access_token的url
        $token_url = $this->getAccessTokenUrl() . '?' . http_build_query($keysArr);
        $response = json_decode(file_get_contents($token_url));
        if (isset($response->error)) {
            $this->error->showError($response->error, $response->error_description);
        }
        
        $this->recorder->write("access_token", $response->access_token);
        return $response->access_token;
    }

    /**
     * get_access_token
     * 获得access_token
     *
     * @param
     *            void
     * @since 5.0
     * @return string 返加access_token
     */
    public function get_access_token()
    {
        return $this->recorder->read("access_token");
    }

    /**
     * 使参数失效
     */
    public function invalidate()
    {
        $this->recorder->initData()->save();
    }
}
